<template>
  <div class="login-register-container" style="margin-top: 68px">
    <h1>{{ isLogin ? "登录" : "注册" }}</h1>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label for="username">用户名</label>
        <input type="text" id="username" v-model="form.username" required />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input type="password" id="password" v-model="form.password" required />
      </div>
      <div v-if="!isLogin" class="form-group">
        <label for="confirmPassword">确认密码</label>
        <input
          type="password"
          id="confirmPassword"
          v-model="form.confirmPassword"
          required
        />
      </div>
      <button type="submit">{{ isLogin ? "登录" : "注册" }}</button>
    </form>
    <p>
      {{ isLogin ? "没有账号？" : "已有账号？" }}
      <a href="#" @click.prevent="toggleMode">{{
        isLogin ? "注册" : "登录"
      }}</a>
    </p>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useUserStore } from "../stores/user";
import { useRouter } from "vue-router";

const userStore = useUserStore();
const router = useRouter();
const isLogin = ref(true);
const form = reactive({
  username: "",
  password: "",
  confirmPassword: "",
});

const toggleMode = () => {
  isLogin.value = !isLogin.value;
};

const handleSubmit = async () => {
  if (isLogin.value) {
    const success = await userStore.login(form.username, form.password);
    if (success) {
      router.push("/");
    }
  } else {
    if (form.password !== form.confirmPassword) {
      alert("两次输入的密码不一致");
      return;
    }
    const success = await userStore.register(form.username, form.password);
    if (success) {
      alert("注册成功，请登录");
      isLogin.value = true;
    }
  }
};
</script>

<style scoped>
.login-register-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
.form-group {
  margin-bottom: 15px;
}
label {
  display: block;
  margin-bottom: 5px;
}
input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
button {
  width: 100%;
  padding: 10px;
  background-color: #9a0e14;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:hover {
  background-color: #7a0a0f;
}
</style>
